package com.mingte.manghe.interceptory;

import com.alibaba.fastjson.JSONObject;
import com.mingte.manghe.common.ResponseResult;
import com.mingte.manghe.dto.TeaUserDTO;
import com.mingte.manghe.exception.UserNotExistExecption;
import com.mingte.manghe.utils.JwtUtils;
import com.mingte.manghe.utils.RedisUtils;
import com.mingte.manghe.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：luxinsheng
 * @Email ：282860642@qq.com
 * @date ：Created in 2021/12/21 11:35
 * @description：登录拦截
 * @modified By：
 * @version: $
 */
public class LoginInterceptor implements AsyncHandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String access_mh_token = request.getHeader("access_mh_token");

        try {
            if(StringUtils.isNotEmpty(access_mh_token)
                    && checkJwtToken(access_mh_token)){
                return true;
            }else{
                ResponseResult.error(response,"请先登录");
            }
        }catch (Exception exception){
            //exception.printStackTrace();
            ResponseResult.error(response,exception.getMessage());
        }
        return false;
    }

    /**
     * 验证token是否合格
     * @param token
     * @return
     */
    public boolean checkJwtToken(String token)throws RuntimeException{
        // 验证 token
        if(JwtUtils.checkSign(token)){
            String userId = JwtUtils.getUserId(token);
            if(StringUtils.isNotEmpty(userId)){
                TeaUserDTO teaUserDTO = (TeaUserDTO)redisUtils.get(userId);
                if(null != teaUserDTO){
                    return teaUserDTO.getAccessMhToken().equals(token);
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
